package com.yuand.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

/**
 * @author yuandong
 * @date 2021/12/7 10:19
 */
@Slf4j
public class HttpUtils {

    /**
     * 获取请求头header中的参数
     * TreeMap实现了SortedMap接口，保证了有序性。默认的排序是根据key值进行升序排序
     * @param request
     * @return
     */
    public static SortedMap<String, String> getHeaderParams(HttpServletRequest request) throws IOException {
        SortedMap<String, String> sortedMap = new TreeMap<>();
        //获取Header上的参数
        String appKey = request.getHeader("Haiot-appKey");
        sortedMap.put("Haiot-appKey", appKey);
        return sortedMap;
    }


    /**
     * 获取url中的参数,该参数使用LinkedHashMap接收
     * @param request
     * @return
     */
    public static LinkedHashMap<String, List<String>> getUrlParams(HttpServletRequest request) {

        LinkedHashMap<String, List<String>> params = new LinkedHashMap<>();

        if (!CollectionUtils.isEmpty(request.getParameterMap())) {

            Map<String, String[]> parameterMap = request.getParameterMap();

            //获取GET请求参数,以键值对形式保存
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {//{username:[xx],password:[xx]}
                for (String value : entry.getValue()) {
                    if(value.indexOf(",")==-1){
                        params.put(entry.getKey(), Lists.newArrayList(entry.getValue()));
                    }else{
                        String[] split = value.split(",");
                        params.put(entry.getKey(),Lists.newArrayList(split));
                    }
                }
            }
        }
        return params;
    }


    //获取post请求的请求体---body中的数据
    public static String getRequestBody(HttpServletRequest request) throws IOException {
        // 分别获取了request inputstream中的body信息、parameter信息
        //获取body（对应@RequestBody）
        if (request instanceof BodyReaderHttpServletRequestWrapper) {
            BodyReaderHttpServletRequestWrapper requestWrapper = new BodyReaderHttpServletRequestWrapper(request);
            try {
                JSONObject data = JSONObject.parseObject(requestWrapper.getBody());
                if (data != null) {
                    //获取POST请求的JSON参数,以键值对形式保存
                    for (Map.Entry<String, Object> entry : data.entrySet()) {
                        System.out.println("key>>>>" + entry.getKey() + "value>>>" + entry.getValue().toString());
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return requestWrapper.getBody();
        } else {
            return "";
        }
    }

    /**
     * 获取请求方IP
     *
     * @param request 请求
     * @return 客户端Ip
     */
    public static String getClientIp(HttpServletRequest request) {
        String xff = request.getHeader("x-forwarded-for");
        if (xff == null) {
            return request.getRemoteAddr();
        }
        return xff;
    }

    /**
     * 主要功能:获取请求方IP
     * 注意事项:无
     *
     * @param request 请求
     * @return String IP
     */
    public static String getIpAddrByRequest(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 获取完整的请求URL
     *
     * @param request 请求
     * @return URL
     */
    public static String getRequestUrl(HttpServletRequest request) {
        return request.getRequestURL().toString();
    }



}
